package com.jd.config;

import com.jd.UserInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Collection;
 
public class TenantInfoHolder {
 
	 private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>() {
	        /**
	         * 默认tenantId
	         */
	        @Override
	        protected String initialValue() {
	            return "";
	        }
	};


	 /**
     * 切换租户
     * @param
     */
    public static void setTenantId(String tenantId) {
        contextHolder.set(tenantId);
    }
 
    /**
     * 获取当前租户
     * @return
     */
    public static String getTenantId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication != null && authentication.getPrincipal() != null
              && !AnonymousAuthenticationToken.class.isAssignableFrom(authentication.getClass())) {
        	UserInfo userInfo = (UserInfo)authentication.getPrincipal();
	        if(userInfo != null) {
	        	/**
	        	 * 超级管理员优先从contextHolder中取
	        	 */
	        	Collection<? extends GrantedAuthority> authorities = userInfo.getAuthorities();
	        	if(authorities != null) {
	        		
        			if(authorities.contains(new SimpleGrantedAuthority("superAdmin"))){
		        		if(StringUtils.isNotBlank(contextHolder.get())) {
		        			return contextHolder.get();
		        		}
        			}
	        	}
	        	return userInfo.getTenantId();
        	}
        }
        
        return contextHolder.get();
    }
 
    /**
     * 清空当前租户信息
     */
    public static void clearTenantId() {
        contextHolder.remove();
    }
 
	
}
